import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sports_new/controller/navigation_logic.dart';
import 'package:sports_new/controller/match/list/match_page_logic.dart';
import 'package:sports_new/controller/match/list/zq_match_filter_logic.dart';
import 'package:sports_new/controller/match/list/zq_view_logic.dart';
import 'package:sports_new/resources/styles.dart';
import 'package:sports_new/utils/constant.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/view/loading/loading_match_list.dart';
import 'package:sports_new/view/match/match_filter_float_widget.dart';
import 'package:sports_new/view/match/soccer/zq_match_cell.dart';
import 'package:sports_new/widgets/loading/loading_widget.dart';
import 'package:sports_new/widgets/loading/no_data_widget.dart';
import 'package:umeng_apm_sdk/umeng_apm_sdk.dart';
import 'package:visibility_detector/visibility_detector.dart';

import '../../../utils/sp_utils.dart';
import '../../../widgets/ads_label.dart';
import '../../../widgets/header_delegate.dart';

class ZqBeginView extends StatefulWidget {
  const ZqBeginView({super.key});

  @override
  State<ZqBeginView> createState() => _ZqBeginViewState();
}

class _ZqBeginViewState extends State<ZqBeginView> {
  final logic = Get.put(
      ZqViewLogic(ZqMatchType.begin, Constant.matchFilterTagBegin),
      tag: Constant.matchFilterTagBegin,permanent: true);
  final scrollC = ApmScrollController();

  @override
  void initState() {
    super.initState();
    scrollC.addListener(() {
      Get.find<NavigationLogic>().onMatchPageScroll();
    });
  }

  // @override
  // void didChangeDependencies() {
  //   super.didChangeDependencies();
  //   PrimaryScrollController.of(context).addListener(didScroll);
  // }

  // @override
  // void deactivate() {
  //   PrimaryScrollController.of(context).removeListener(didScroll);
  //   super.deactivate();
  // }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<ZqViewLogic>(
        tag: Constant.matchFilterTagBegin,
        builder: (_) {
          return VisibilityDetector(
            key: const Key('begin'),
            onVisibilityChanged: (VisibilityInfo info) {
              if(info.visibleBounds.isEmpty && logic.groupMatchList != null) {
                logic.getMatch();
              }
            },
            child: Stack(
              children: [
                EasyRefresh.builder(
                  controller: logic.refreshC,
                  header:
                      Styles.refreshHeader(position: IndicatorPosition.locator),
                  onRefresh: () async {
                    Utils.onEvent('bspd_sx');
                    await logic.getMatch();
                  },
                  childBuilder: (BuildContext context, ScrollPhysics physics) =>
                      CustomScrollView(
                    physics: physics,
                    slivers: [
                      const HeaderLocator.sliver(),
                      if (SpUtils.matchZqAds?[1].hasValue == false ||
                          DateTime.now()
                                  .difference(
                                      DateTime.parse(SpUtils.matchZqAds![1]))
                                  .inHours >
                              24)
                        SliverToBoxAdapter(
                          child: AdsLabel(
                            adsTag: "match_zq_赛中",
                            close: 1,
                            tapType: 'match_advertising',
                            tagParam: "赛中",
                            margin: const EdgeInsets.fromLTRB(8, 8, 8, 0),
                            onClose: () => setState(() {}),
                          ),
                        ),
                      LoadingWidget<int>(
                        data: logic.groupMatchList?.length ?? 0,
                        isLoading: logic.firstLoad,
                        loading: const LoadingMatchList.sliver(sportsId: 1),
                        noData: NoDataWidget.sliver(
                          tip: logic.quickFilter == QuickFilter.yiji
                              ? '暂无一级比赛'
                              : (logic.quickFilter == QuickFilter.jingcai
                              ? '暂无竞足比赛'
                              : '没有进行中的比赛~'),
                        ),
                        child: () => const SliverToBoxAdapter(),
                      ),
                      if ((logic.groupMatchList?.length ?? 0) > 0)
                      ...List.generate(
                        logic.dayList?.length ?? 0,
                        (index) => SliverMainAxisGroup(slivers: [
                          SliverPersistentHeader(
                            pinned: true,
                            delegate: HeaderDelegate(
                              extent: 28,
                              child: Styles.matchListGroupHeader(
                                logic.dayList![index]
                              )
                            )
                          ),
                          SliverList(
                            delegate: SliverChildBuilderDelegate(
                              childCount: logic.groupMatchList?[index].length ?? 0,
                              (context, i) => ZqMatchCell(
                                logic.groupMatchList![index][i], logic
                              )
                            )
                          )
                        ])
                      ),
                      SliverToBoxAdapter(
                        child: Container(height: 80),
                      )
                    ],
                  ),
                ),
                Positioned(
                    bottom: 40,
                    child: MatchFilterFloatWidget(
                      0,
                      logic.firstLoad,
                      logic.quickFilter,
                      onTap: (index) {
                        logic.onSelectMatchType(index);
                      },
                    )),
                Styles.matchListBottomBar(
                    logic.hideMatchNum != 0 && !logic.isBottomHide,
                    logic.hideMatchNum, onClose: () {
                  Utils.onEvent('bspd_sxfc_gb');
                  logic.onCloseBottomBar();
                }, onDefault: () {
                  Utils.onEvent('bspd_sxfc_hf');
                  logic.onSelectDefaultMatch();
                })
              ],
            ),
          );
        });
  }

  didScroll() {
    Get.find<NavigationLogic>().onMatchPageScroll();
  }
}
